<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Collection
 *
 * @author ketu
 */
class Zhishidi_Dailydeals_Model_Mysql4_Deals_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract {

    protected function _construct() {
        $this->_init('zhishidi_dailydeals/deals');
    }

    public function joinProducts() {
        $tableName = Mage::getSingleton('core/resource')->getTableName('catalog/product');
        $productResource = Mage::getResourceSingleton('catalog/product');
        $nameAttr = $productResource->getAttribute('name');
        $nameAttrId = $nameAttr->getAttributeId();
        $nameAttrTable = $nameAttr->getBackend()->getTable();



        $this->getSelect()->joinLeft(
                        array('_table_product_name' => $nameAttrTable),
                        '(_table_product_name.entity_id = main_table.product_id)
                             AND (_table_product_name.attribute_id = ' . (int) $nameAttrId . ')',
                        array('product_name' => '_table_product_name.value')
                )
                ->joinLeft(
                        array('_table_product_sku' => $tableName),
                        '(_table_product_name.entity_id = _table_product_sku.entity_id)',
                        array('product_sku' => '_table_product_sku.sku')
        );

        return $this;
    }

    public function setDateRange($from) {
        if ($from)
            $this->getSelect()->where("main_table.deal_to >= ?", $from);
        return $this;
    }

    public function addVisibleFilter($visible = 'public') {
        $this->getSelect()->where('main_table.deal_status = ?', $visible);
        return $this;
    }
    
    public function addStoreFilter($store, $withAdmin = true) {
        if ($store instanceof Mage_Core_Model_Store) {
            $store = array($store->getId());
        }
        $tableName = $this->getTable('zhishidi_dailydeals/stores');
        $this->getSelect()->joinLeft(
                array('_table_deals_stores' => $this->getTable('zhishidi_dailydeals/stores')),
                'main_table.deal_id = _table_deals_stores.deal_id',
                array('store_id' => '_table_deals_stores.store_id')
        )->where('_table_deals_stores.store_id in (?)', ($withAdmin ? array(0, $store) : $store));

        return $this;
    }

}

?>
